package com.emperor.category.app;

import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;

import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.hibernate.Session;

import com.emperor.category.logic.Category;
import com.emperor.category.logic.CategoryModel;
import com.emperor.core.app.App;
import com.emperor.core.app.AppBase;
import com.emperor.core.app.AppConstant;
import com.emperor.customer.app.CustomerAppCtrl;
import com.emperor.inventory.app.InventoryAppCtrl;
import com.emperor.util.HibernateUtil;
import com.swtdesigner.SWTResourceManager;

public class CategoryAppMgm extends AppBase implements App {

	private Text text_3;
	private Text text_1;
	private Text text_2;
	private Text text;
	protected Shell shell;
	public static Logger log = Logger.getLogger(CategoryAppMgm.class);

	public CategoryAppMgm() {
		super();
	}

	public CategoryAppMgm(Map<String, Object> params) {
		super();
		this.params = params;
	}

	/**
	 * Launch the application
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			CategoryAppMgm window = new CategoryAppMgm();
			window.open();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Open the window
	 */
	public void open() {
		final Display display = Display.getDefault();
		createContents();
		shell.open();
		shell.layout();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch())
				display.sleep();
		}
	}

	/**
	 * Create contents of the window
	 */
	protected void createContents() {
		shell = new Shell();
		shell.setBackgroundMode(SWT.INHERIT_DEFAULT);
		shell.setBackgroundImage(SWTResourceManager.getImage(
				CategoryAppMgm.class, "/img/main.jpg"));
		shell.setImage(SWTResourceManager.getImage(CategoryAppMgm.class,
				"/img/iMac OSX.png"));
		shell.setSize(1000, 700);
		shell.setText("Update Category");

		initScreen(shell, getParams());

		final Composite composite = new Composite(shell, SWT.NONE);
		composite.setBounds(0, 50, 992, 284);

		final Button resetButton = new Button(composite, SWT.NONE);
		resetButton.setLocation(229, 207);
		resetButton.setSize(80, 30);
		resetButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				getShell().close();
			}
		});
		resetButton.setImage(SWTResourceManager.getImage(CategoryAppMgm.class,
				"/img/Refresh.png"));
		resetButton.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont(
				"Segoe UI", 12, SWT.NORMAL));
		resetButton.setText("Reset");

		final Button saveButton = new Button(composite, SWT.NONE);
		saveButton.setLocation(128, 207);
		saveButton.setSize(90, 30);
		saveButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				try {
					Category category = new CategoryModel();

					Session session = HibernateUtil.getSessionFactory()
							.getCurrentSession();
					category = (Category) setModel(composite, "cat", category);

					category = (Category) session.get(CategoryModel.class,
							category.getId());

					category = (Category) setModel(composite, "cat", category);
					log.debug(category.getClass().getSimpleName() + " : "
							+ category.getValues().toString());

					List<String> errors = CategoryAppNew.validateForm(category);
					if (errors.isEmpty()) {
						category = (Category) preUpdate(category, getParams());

						int rowCount = doUpdate(category);

						if (rowCount == 1) {
							// getParams().put(InventoryAppCtrl.INVENTORY_MSG,
							// "Category updated successfully.");
							message(getShell(), "Update Success.",
									"Category updated successfully.");

							int type = (Integer) getParams().get(
									CategoryAppCtrl.CATEGORY_TYPE);
							String[] ctrlAction = CategoryAppNew
									.switchCtrlAction(type);
							getParams().put(AppConstant.APPCTRL, ctrlAction[0]);
							getParams().put(AppConstant.ACTION, ctrlAction[1]);
							getShell().close();
						}
					} else {
						message(getShell(), "Update Error.", errors.get(0),
								SWT.ICON_ERROR | SWT.OK);
					}
				} catch (Exception ex) {
					log.error("Unable to update category.", ex);
					message(getShell(), "Update Error.", ex.getMessage());
				}
			}
		});
		saveButton.setImage(SWTResourceManager.getImage(CategoryAppMgm.class,
				"/img/Edit.png"));
		saveButton.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont(
				"Segoe UI", 12, SWT.NORMAL));
		saveButton.setText("Update");

		final Label messageLabel = new Label(composite, SWT.NONE);
		messageLabel
				.setText("Please update the category details below and click Save to save the changes.");

		messageLabel.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont(
				"Segoe UI", 12, SWT.NORMAL));
		messageLabel.setBounds(10, 0, 972, 20);

		final Label nameLabel = new Label(composite, SWT.NONE);
		nameLabel.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont(
				"Segoe UI", 12, SWT.NORMAL));
		nameLabel.setText("Name");
		nameLabel.setBounds(10, 29, 45, 20);

		final Label descriptionLabel = new Label(composite, SWT.NONE);
		descriptionLabel.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont(
				"Segoe UI", 12, SWT.NORMAL));
		descriptionLabel.setText("Description");
		descriptionLabel.setBounds(10, 65, 80, 20);

		text = new Text(composite, SWT.BORDER);
		text.setToolTipText("cat_name");
		text.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont("Segoe UI",
				12, SWT.NORMAL));
		text.setBounds(128, 26, 407, 30);

		text_2 = new Text(composite, SWT.WRAP | SWT.V_SCROLL | SWT.MULTI
				| SWT.BORDER);
		text_2.setToolTipText("cat_desc");
		text_2.setBounds(128, 62, 407, 139);
		text_2.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont(
				"Segoe UI", 12, SWT.NORMAL));

		text_1 = new Text(composite, SWT.BORDER);
		text_1.setVisible(false);
		text_1.setToolTipText("cat_id");
		text_1.setBounds(598, 55, 80, 25);

		text_3 = new Text(composite, SWT.BORDER);
		text_3.setVisible(false);
		text_3.setToolTipText("cat_status");
		text_3.setBounds(598, 86, 80, 25);

		//
		int type = (Integer) getParams().get(CategoryAppCtrl.CATEGORY_TYPE);
		String[] ctrlAction = CategoryAppNew.switchCtrlAction(type);
		buildStandardMenu(getShell(), getParams(), ctrlAction[0], ctrlAction[1]);
		populateControls(composite);
	}

	private void populateControls(Composite composite) {
		if (getParams().get(CategoryAppCtrl.CATEGORY_ID) == null) {
			getParams().put(CategoryAppCtrl.CATEGORY_MSG,
					"Unable to display category, category ID not found.");

			getParams().put(AppConstant.APPCTRL,
					InventoryAppCtrl.INVENTORY_CTRL);
			getParams().put(AppConstant.ACTION, InventoryAppCtrl.INVENTORY_ENQ);
			getShell().close();
		}

		try {
			Long id = (Long) getParams().get(CategoryAppCtrl.CATEGORY_ID);

			Session session = HibernateUtil.getSessionFactory()
					.getCurrentSession();
			session.beginTransaction();

			Category category = (Category) session.get(CategoryModel.class, id);
			if (category != null && category.getId() != null) {
				setControls(composite, "cat", category);
			}
		} catch (Exception e) {
			log.error("Unable to populate category composite.", e);

			getParams().put(AppConstant.APPCTRL,
					InventoryAppCtrl.INVENTORY_CTRL);
			getParams().put(AppConstant.ACTION, InventoryAppCtrl.INVENTORY_ENQ);
			getShell().close();
		}
	}

	private int doUpdate(Category category) throws Exception {
		int rowCount = 0;
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		try {
			session.beginTransaction();

			session.saveOrUpdate(category);
			log.debug(category.getClass().getSimpleName() + " : "
					+ category.getValues().toString());
			rowCount++;

			session.getTransaction().commit();
		} catch (Exception e) {
			session.getTransaction().rollback();
			log.error("Unable to do update category.", e);
			throw e;
		}
		return rowCount;
	}

	public Shell getShell() {
		return shell;
	}

}
